package com.zmxstudy.gzu.controller;

import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.zmxstudy.gzu.domain.TbSpu;
import com.zmxstudy.gzu.domain.es.Query;
import com.zmxstudy.gzu.domain.es.SkuInfo;
import com.zmxstudy.gzu.mapper.TbSpuMapper;
import com.zmxstudy.gzu.service.SkuService;
import com.zmxstudy.gzu.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;


@Tag(name = "ES查询")
@RestController
@RequestMapping("/product-service/es")
public class ESController {
    @Resource
    private SkuService skuService;

    @Resource
    TbSpuMapper tbSpuMapper;
    /**
     * 导入数据
     * @return
     */
    @Operation(summary = "数据同步")
    @PostMapping("/import")
    @ResponseBody
    public Result imports(){
        skuService.importSku();
        return Result.success();
    }


    @PostMapping("/abc")
    @ResponseBody
    public void abc(){
        skuService.abc();

    }



    @Operation(summary = "模糊查询,Json格式输入：例如{ ”input“<搜索框模糊搜索>:”手机“}<可添加其他字段进行多条件、价格区间、排序等聚合查询>")
    @SneakyThrows
    @PostMapping("/search")
    public Result search(@RequestBody Query query){
        double gt=0;
        double lt=99999999;
        if (query.getGt() == null){
            query.setGt(gt);
        }
        if (query.getLt() == null){
            query.setLt(lt);
        }


        SearchResponse<SkuInfo> mapSearchResponse = skuService.search(query);

        List<SkuInfo> list = new ArrayList<>();

        for (Hit<SkuInfo> i : mapSearchResponse.hits().hits())
        {
            if (i.source().getName()!=null){
                list.add(i.source());
            }
        }

        List<TbSpu> tbSpuList = new ArrayList<>();
        System.out.println(list);
        System.out.println("----------------------------------");
        for (SkuInfo item:list) {
            System.out.println(item);
            int judge = 0;
            for (TbSpu i:tbSpuList) {
                if (i != null && item.getSpuId().equals(i.getId())){
                    judge = judge + 1;
                }
            }
            if (judge == 0){
                TbSpu tbSpu = tbSpuMapper.selectById(item.getSpuId());
                if (tbSpu != null){
                    tbSpu.setPrice(item.getPrice());
                }
                tbSpuList.add(tbSpu);
            }
        }

        System.out.println("----------------------------------");
        for (TbSpu i:tbSpuList) {
            System.out.println(i);
        }
        return Result.success(tbSpuList);
    }

}
